package com.lancoo.klgcourseware.ui.fragment.basicTrain;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.media.MediaPlayer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.lzyzsd.circleprogress.DonutProgress;
import com.google.gson.Gson;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.WordArticulation;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgConstant;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.entity.bean.SpellCharacterBean;
import com.lancoo.klgcourseware.manager.KlgLocalMediaManager;
import com.lancoo.klgcourseware.ui.activity.KlgBasicTrainActivity;
import com.lancoo.klgcourseware.ui.adapter.FillSpellCharacterAdapter;
import com.lancoo.klgcourseware.ui.widget.CountTimeView;
import com.lancoo.klgcourseware.utils.KlgTrainUtils;
import com.lancoo.klgcourseware.utils.klog.KLog;
import com.stkouyu.entity.LgEvaluateObj;
import com.tt.LancooSkEgnManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2019/8/15 18:34
 * Description:填空拼写
 */
public class FillSpellTrainFragment extends BasicTrainBaseFragment implements KlgLocalMediaManager.OnPlayListener{

    private boolean isQuality;
    private int hideIndex=-1,hideSecondIndex=-1,totalTrainWordCount;//隐藏第几节音节，隐藏第几节音节（备用）,总共需要训练的字母个数
    private String[] splitFillSpell;
    private KlgLocalMediaManager resultMediaManager;

    private enum SpellState{
        THREESOCOND,TRAINING,RESULT
    }

    private static final String TAG = "SpellTrainFragment";
    private final int splitTime=700;
    private KlgCommonBean commonBean;
    protected List<SpellCharacterBean> spellCharacterBeans;
    private int totalTime=3000;
    private FillSpellCharacterAdapter mAdapter;
    private DonutProgress donutProgress;
    private ImageView img_pause;
    private RelativeLayout rl_recorder,rl_result,rl_spell;
    private String evaluationContent;
    private RecyclerView mRecyclerView;
    private int grade;
    private TextView tv_trainAgain,tv_enterPhoneticTrain;
    private SpellState spellState= SpellState.THREESOCOND;
    private CountTimeView countTimeView;
    private TextView tv_alert,tv_giveUpTrain;
    private ImageView img_completeLogo;


    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_spell_train;
    }

    @Override
    protected void initView(View view) {
        commonBean = (KlgCommonBean) getArguments().getSerializable(KlgBasicTrainActivity.KEY_KLGCOMMONBEN);
        currentTrainTag=TRAINTAG_SPELL_FILL;
        if(commonBean==null){
            showEmptyLayout();
        }else{
            showData(view);
            mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if(mRecyclerView!=null){
                        mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        enableStartTrain(0);
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-time<500){
            return;
        }
        time=System.currentTimeMillis();
        super.onClick(v);
        int id=v.getId();
        if(id==R.id.tv_train_again){
            pauseSecondTimer();
            enableStartTrain(0);
            resetSpellTrainStyle();
        }else if(id==R.id.tv_enter_phonetic_train){
            pauseSecondTimer();
            resetSpellTrainStyle();
            enterNextTrainModel();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(tv_enterPhoneticTrain!=null){
            tv_trainAgain.setText(R.string.klg_read_again);
            tv_enterPhoneticTrain.setText(R.string.klg_enter_phonetic_train);
        }
        pauseMeidaPlayer();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(resultMediaManager!=null){
            resultMediaManager.release();
        }
    }

    protected void showData(View view){
        ViewStub viewStub = view.findViewById(R.id.viewstub_main_data);

        if(viewStub!=null){
            viewStub.inflate();
        }
        splitSpellData();
        resultMediaManager=new KlgLocalMediaManager();
        mRecyclerView = view.findViewById(R.id.recycler_view_spell);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
        mAdapter = new FillSpellCharacterAdapter(getContext(),spellCharacterBeans);
        mAdapter.setTrainModel(true,false);
        mRecyclerView.setAdapter(mAdapter);

        TextView tv_usPhonetic = view.findViewById(R.id.tv_us_phonetic);
        tv_usPhonetic.setText(commonBean.getUs_phonetic());
        try{
            Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "klg_droid_sans_bold.ttf");
            tv_usPhonetic.setTypeface(typeFace);
        }catch (Exception e){

        }
        TextView tv_meaning = view.findViewById(R.id.tv_meaning);
        tv_meaning.setText(commonBean.getExplain());
        tv_meaning.setMovementMethod(new ScrollingMovementMethod());
        donutProgress = view.findViewById(R.id.donut_progress);
        img_pause = view.findViewById(R.id.img_pause);
        rl_spell = view.findViewById(R.id.rl_spell);
        rl_recorder = view.findViewById(R.id.rl_recorder);
        rl_result=view.findViewById(R.id.rl_spell_result);
        img_pause.setOnClickListener(this);
        donutProgress.setProgress(0);
        donutProgress.setMax(totalTime);
//        ImageView img_recorder=view.findViewById(R.id.img_recorder);
//        AnimationDrawable animation = (AnimationDrawable)img_recorder.getDrawable();
//        animation.start();
        rl_recorder.setVisibility(View.GONE);

        tv_trainAgain = view.findViewById(R.id.tv_train_again);
        tv_enterPhoneticTrain = view.findViewById(R.id.tv_enter_phonetic_train);
        tv_trainAgain.setText(R.string.klg_read_again);
        countTimeView = view.findViewById(R.id.counttime_view);
        tv_alert = view.findViewById(R.id.tv_spell_memory_write_alert);
        tv_giveUpTrain = view.findViewById(R.id.tv_pass_train);
        tv_giveUpTrain.setOnClickListener(this);
        img_completeLogo = view.findViewById(R.id.img_complete_logo);
        view.findViewById(R.id.img_alert).setVisibility(getArguments().getBoolean(KEY_IS_ALERT)?View.VISIBLE:View.GONE);
        ImageView img_alert=view.findViewById(R.id.img_alert);
        img_alert.setImageResource(R.mipmap.klg_more_spellblank);
        resetSpellTrainStyle();
    }


    /**
     * 单词拆分，作答总时长统计
     */
    private void splitSpellData(){
        spellCharacterBeans=new ArrayList<>();
        totalTime=0;
        StringBuilder stringBuilder=new StringBuilder();
        WordArticulation wordArticulation = (WordArticulation) getArguments().getSerializable(KEY_SPELL_ARTICULATION);
        String syllable = wordArticulation.getSyllable();
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(KlgDbConstant.SP_KNOWLEDGE_COURSE, Context.MODE_PRIVATE);
        hideIndex=sharedPreferences.getInt(KlgDbConstant.SP_FILL_SPELL_HIDE_FIRSET_INDEX,-1);
        hideSecondIndex=sharedPreferences.getInt(KlgDbConstant.SP_FILL_SPELL_HIDE_SECOND_INDEX,-1);

        int index=1;
        boolean haiPoint=false;
        boolean haiLine=false;
        splitFillSpell = syllable.split("·");
        int pointShowIndex=0;
        Log.e("aaaa",syllable+ splitFillSpell.length+"隐藏第"+ hideIndex +"段,"+"隐藏第"+hideSecondIndex+"段");
        SpellCharacterBean lastCharacterBean=null;
        //拼写,快速环节数据组装
        for (int i = 0; i < syllable.length(); i++) {

            if(TextUtils.equals("·",syllable.charAt(i)+"")){
                haiPoint=true;
                pointShowIndex++;
                continue;
            }
            if(TextUtils.equals("-",syllable.charAt(i)+"")){
                haiLine=true;
                pointShowIndex++;
                continue;
            }
            if(TextUtils.equals("'",syllable.charAt(i)+"")){
                if(lastCharacterBean!=null){
                    lastCharacterBean.setSpecialChar(syllable.charAt(i)+"");
                    lastCharacterBean.setHasSpecialChar(true);
                }
                continue;
            }
            if(TextUtils.equals(".",syllable.charAt(i)+"")){
                if(lastCharacterBean!=null){
                    lastCharacterBean.setSpecialChar(syllable.charAt(i)+"");
                    lastCharacterBean.setHasSpecialChar(true);
                }
                continue;
            }
            SpellCharacterBean spellCharacterBean=new SpellCharacterBean();
            spellCharacterBean.setCharacter(syllable.charAt(i)+"");
            spellCharacterBean.setTimeLength(splitTime*(index));
            spellCharacterBean.setHasPoint(haiPoint);
            spellCharacterBean.setHasLine(haiLine);
            spellCharacterBean.setHideWord((hideIndex!=-1&&pointShowIndex== hideIndex) ||(hideSecondIndex!=-1&&hideSecondIndex==pointShowIndex));
            spellCharacterBeans.add(spellCharacterBean);
            totalTime+=splitTime;
            totalTrainWordCount++;
            if(spellCharacterBean.isHideWord()){
                stringBuilder.append(syllable.charAt(i)+" ");
            }
            index++;
            haiPoint=false;
            haiLine=false;
            lastCharacterBean=spellCharacterBean;
        }
        totalTime+=1000;
        stringBuilder.append(" "+wordArticulation.getKlgName());
        evaluationContent = stringBuilder.toString();



    }

    /**
     * 重置拼写训练样式
     */
    private void resetSpellTrainStyle(){
        if(rl_recorder==null){
            return;
        }
        spellState= SpellState.THREESOCOND;
        img_pause.setVisibility(View.GONE);
        mAdapter.setTrainModel(true,false);
        rl_recorder.setVisibility(View.GONE);
        rl_result.setVisibility(View.GONE);
        rl_spell.setBackgroundResource(R.mipmap.klg_icon_articulate_bg);
        donutProgress.setVisibility(View.VISIBLE);
        recorderProgress=0;
        donutProgress.setProgress(0);
        tv_alert.setText(R.string.klg_start_spell_fill_train_alert);
        convertView.findViewById(R.id.rl_count_time).setVisibility(View.GONE);
        tv_giveUpTrain.setVisibility(View.INVISIBLE);
        img_completeLogo.setVisibility(View.GONE);
        countTimeView.setVisibility(View.VISIBLE);
        for (SpellCharacterBean spellCharacterBean:spellCharacterBeans){
            spellCharacterBean.setTrain(false);
        }
        showIndex=-1;
    }

    /**
     * 暂停单词拼读训练
     */
    private void pauseSpellTrain(){
        if(rl_recorder==null){
            return;
        }
        rl_recorder.setVisibility(View.VISIBLE);
        donutProgress.setVisibility(View.INVISIBLE);
        donutProgress.setProgress(0);
        img_pause.setVisibility(View.VISIBLE);
    }

    /**
     * 训练结果展示
     */
    private void showSpellTrainResult(int resultMessage){
        if(rl_recorder==null){
            return;
        }
        rl_recorder.setVisibility(View.GONE);
        tv_alert.setText(isQuality?R.string.klg_result_correct_spell:R.string.klg_result_error_spell);
        convertView.findViewById(R.id.rl_count_time).setVisibility(View.VISIBLE);
        countTimeView.setAngle(0,TRAINRESULT_TIME);
        if(resultMessage!=0){
            tv_alert.setText(resultMessage);
            tv_giveUpTrain.setVisibility(View.VISIBLE);
        }
        if(isQuality){
            img_completeLogo.setVisibility(View.VISIBLE);
            countTimeView.setVisibility(View.GONE);
            if(getArguments().getBoolean(KEY_ISMORE_ENTER)){
                tv_alert.setText(R.string.klg_result_exit_train_for_spell_fill);
            }else{
                tv_alert.setText(R.string.klg_spell_fill_correct);
            }
            tv_giveUpTrain.setVisibility(View.GONE);
        }else{
            img_completeLogo.setVisibility(View.GONE);
            countTimeView.setVisibility(View.VISIBLE);
            tv_giveUpTrain.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 3s倒计时
     * @param progress
     * @param totalProgress
     */
    protected void updateCountTime(int progress,int totalProgress){
//        Log.e("aaaaa","progress:"+progress+"......>"+totalProgress);
        if(convertView==null){
            return;
        }
        convertView.findViewById(R.id.rl_count_time).setVisibility(progress==totalProgress?View.GONE:View.VISIBLE);
        countTimeView.setAngle(progress,totalProgress);
    }


    /**
     *开始训练 从滴水声后
     */
    protected void startTrain(){
        Log.e(TAG,"onTrainStart");
        spellState= SpellState.TRAINING;
        if(rl_recorder==null){
            return;
        }
        recorderProgress=0;
        showIndex=-1;
        rl_recorder.setVisibility(View.VISIBLE);
        upDateRecordProgress();
        startCountTimeTimer();
        startSpeechEvaluation(evaluationContent,"");
    }

    private int showIndex=-1;
    private boolean isTrainShow;
    /**
     * 更新录音作答时长进度
     */
    protected void upDateRecordProgress(){
        if(donutProgress!=null){
            donutProgress.setProgress(recorderProgress);
//            if(recorderProgress>(mAdapter.getShowIndex()+1)*splitTime){
//                mAdapter.changeRepeat(recorderProgress/splitTime);
//                scrollIndex(mRecyclerView,recorderProgress/splitTime,commonBean.getKlgName().length(),true);
//            }
            if((recorderProgress/splitTime)>showIndex&&showIndex<totalTrainWordCount){
                showIndex++;
                Log.e("aaaa","recorderProgress/splitTime:"+(recorderProgress/splitTime)+"...showIndex:"+showIndex+"....totalTrainWordCount:"+totalTrainWordCount);
                for (SpellCharacterBean spellCharacterBean:spellCharacterBeans){
                    if(spellCharacterBean.isHideWord()&&!spellCharacterBean.isTrain()){
                        spellCharacterBean.setTrain(true);
                        break;
                    }
                }
                mAdapter.changeRepeat(showIndex,totalTrainWordCount);
                isTrainShow=true;
            }
        }
        if(recorderProgress>=totalTime-1000&&isTrainShow){
            isTrainShow=false;
            mAdapter.changeRepeat(-2,totalTrainWordCount);
//            destroyCountTimeTimer();
        }

        if(recorderProgress>=totalTime){
            Log.e("aaaa","作答结束");
            destroyCountTimeTimer();
            stopSpeechEvaluation(true);
        }
        float volume = LancooSkEgnManager.getInstance(getContext()).getVolume();
        audioAnimation((int)volume);

    }

    /**
     * 语音评测成功
     * @param grade
     * @param url
     * @param skegnResult
     */
    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){
        KLog.json(new Gson().toJson(skegnResult));
        spellState= SpellState.RESULT;
        this.grade=grade;
        int index=0,messageId=0;
        isQuality = true;
        //评测结果赋值到对应的字符对象
        for (int i = 0; i <skegnResult.getResult().getWords().size() ; i++) {
            if(i==skegnResult.getResult().getWords().size()-1){
                Log.e("aaaa","最后一个单词 ："+skegnResult.getResult().getWords().get(i).getWord());
                if(isQuality &&skegnResult.getResult().getWords().get(i).getScores().getOverall()< KlgConstant.SCORE_QUALITY){
                    isQuality =false;
                    messageId=R.string.klg_pronounce_unstandard;
                }
                break;
            }
            int spellIndex=-1;
            for (SpellCharacterBean spellCharacterBean:spellCharacterBeans){

                if(spellCharacterBean.isHideWord()){
                    spellIndex++;
                }
                if(spellCharacterBeans.get(i).getCharacter().equals("-")){
                    spellCharacterBean.setScores(100);
                    spellIndex++;
                    continue;
                }
                if(spellIndex==i){
                    spellCharacterBean.setScores(skegnResult.getResult().getWords().get(i).getScores().getOverall());
                    if(!isQuality){
                        break;
                    }
                    if(spellCharacterBean.getScores()<KlgConstant.SCORE_QUALITY){
                        isQuality =false;
                    }
                }
            }
        }
        updateTrainResult(isQuality);
        mAdapter.setTrainModel(false,true);
        rl_spell.setBackgroundResource(isQuality ?R.mipmap.klg_icon_articulate_bg:R.mipmap.klg_icon_articulate_yellow_bg);
        showSpellTrainResult(messageId);
        startSecondTimer();
        quesResultMuiscPlayer(isQuality);
    }


    /**
     * 继续训练
     */
    protected void continueTrain(){
//        startTrainDialogCountTime(0);
        Log.e("aaaa","continueTrain："+spellState);
        if(spellState==SpellState.THREESOCOND){
            resetSpellTrainStyle();
            enableStartTrain(0);
        }else if(spellState== SpellState.TRAINING){
            resetSpellTrainStyle();
            startDripMusic();
        }else{
            startSecondTimer();
        }

    }

    /**
     * 中止当前的训练
     */
    protected void pauseCurrentSubTrain(boolean isReset){
        if(isReset){
            resetSpellTrainStyle();
        }else{
            if(img_pause!=null){
                img_pause.setVisibility(View.VISIBLE);
                donutProgress.setVisibility(View.INVISIBLE);
                convertView.findViewById(R.id.rl_count_time).setVisibility(View.GONE);
            }
        }

    }

    protected void upDateResultCountTime(int progress,int totalProgress){
        countTimeView.setAngle(progress,totalProgress);
        if(progress==totalProgress){
            pauseSecondTimer();
            Log.e("aaaa","暂停。。。。"+isQuality);
            if(!isQuality){//不合格
                resetSpellTrainStyle();
                enableStartTrain(0);
            }else{
                enterNextTrainModel();
            }
        }
    }


    private void audioAnimation(int db){
        try {
            ImageView imgRecorder = convertView.findViewById(R.id.img_recorder);
            LayerDrawable drawable =(LayerDrawable) imgRecorder.getDrawable();
            Drawable clipDrawable = drawable.getDrawable(1);

            clipDrawable.setLevel(KlgTrainUtils.getAudioDBLevel(db));
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    private void pauseMeidaPlayer(){
        if(resultMediaManager!=null){
            resultMediaManager.pause();
        }
    }


    protected void quesResultMuiscPlayer(boolean isCorrect){
        if(resultMediaManager==null){
            return;
        }
        try {
            AssetFileDescriptor assetFileDescriptor = getContext().getAssets().openFd(isCorrect?"klg_record_correct.mp3":"klg_record_error.mp3");
            resultMediaManager.setUpMedia(assetFileDescriptor,this);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onStartError() {

    }

    @Override
    public void onPausePlay() {

    }

    @Override
    public void onSourceError() {

    }

    @Override
    public void onResumePlay() {

    }

    @Override
    public void onStopPlay() {

    }

    @Override
    public void onPrepare() {
        if(resultMediaManager!=null){
            resultMediaManager.start();
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }


}
